<template>
  <Card size="small" class="share-card">
    <profitTotalsChart />
  </Card>
  <Card size="small" class="share-card">
    <Table :rowKey="getRowKey" :expand-column-width="30" :columns="columns" @resizeColumn="resizeColumn" :scroll="{ x: 800, y: tableHeight }" :pagination="false" :data-source="profits" size="small" bordered>
      <template #expandedRowRender="{ record }">
        <div style="margin: 0">
          <profitChart :code="record.ShareCode" />
        </div>
      </template>
      <template #summary>
        <Table.Summary fixed>
          <Table.Summary.Row>
            <Table.Summary.Cell :col-span="2" style="text-align: right; font-weight: bold">总收益</Table.Summary.Cell>
            <Table.Summary.Cell :col-span="7" style="font-weight: bolder">{{ totalRevenue }}</Table.Summary.Cell>
          </Table.Summary.Row>
        </Table.Summary>
      </template>
    </Table>
  </Card>
</template>
<script setup>
  import { useStore } from 'vuex';
  import { ref, reactive, inject, computed, defineAsyncComponent, onMounted } from 'vue';
  import { Card, Table } from 'ant-design-vue';

  const profitChart = defineAsyncComponent(() => import('./components/ProfitChart.vue'));
  const profitTotalsChart = defineAsyncComponent(() => import('./components/ProfitTotalsChart.vue'));

  const $store = useStore();
  const $http = inject('$http');

  const profits = ref([]);
  const totalRevenue = ref(0);
  const columns = reactive([
    {
      title: '序号',
      width: 50,
      align: 'center',
      customRender: ({ record, index }) => {
        return index + 1;
      }
    },
    { title: '股票代号', dataIndex: 'ShareCode', width: 100 },
    { title: '股票名称', dataIndex: 'ShareName', width: 100 },
    { title: '最后核算日期', dataIndex: 'AccountingDate', width: 100 },
    { title: '收益总额', dataIndex: 'ProfitRevenue', width: 100 },
    { title: '开盘价', dataIndex: 'OpeningPrice', width: 100 },
    { title: '收盘价', dataIndex: 'ClosingPrice', width: 100 },
    { title: '总股数', dataIndex: 'Quantity', width: 100 }
  ]);

  const tableHeight = computed(() => {
    return $store.state.area.content.height - 140;
  });

  function getRowKey(record) {
    return 'tr' + record.ShareCode;
  }

  function resizeColumn(w, col) {
    col.width = w;
  }

  async function getProfits() {
    let res = await $http.get('/api/shares/daily/profit/current');

    totalRevenue.value = 0;
    profits.value = res.datas;

    (res.datas || []).forEach(d => (totalRevenue.value += d.ProfitRevenue));
  }

  onMounted(async () => {
    await getProfits();
  });
</script>
